import copy
import os
from typing import List

from common.entitys.context import CommonContext
from common.entitys.monitor import MonitorType, Monitor
from common.enums.Enums import UrlSelf
from database.mapper import monitor_result, stock_info, stock_day_k, stock_day_info, boards_info, \
    monitor_strategy_config
from database.mapper.monitor_result import MonitorResult
from database.mapper.monitor_strategy_config import StrategyCons
from database.mapper.stock_day_info import StockDayInfoDto
from methods import d月macd穿过0方法验证 as month_macd_service
from service import score_service, data_service, msg_service, training_model, users_service
from utils import doc_util, html_util, json_util, date_util, read_config as config, excel_util, price_util, parse_util, \
    cache_util, caiptal_util, dict_util
from webs.service import chart_service

result_path = os.path.join(config.data_path, 'result', '突破均线')
users_path = os.path.join(config.data_path, 'common', 'users')
config_path = os.path.join(config.data_path, 'common', 'config')
trigger_logs_path = os.path.join(config.data_path, 'logs', '突破均线任务1')


# 一键诊断
def diagnosis_stock(code, name):
    stock_dto = get_by_name_or_code(code, name)
    result = html_util.get_form_cross('/diagnosis/stock', 'post', 'form', {'编码': 'stockcode', '名称': 'stockname'}, '诊断')
    if stock_dto.total_val == 0:
        print(stock_dto.code + 'in or out off market')
        return result
    context = CommonContext(stock_dto.code)
    context.name = stock_dto.name
    context.exchange = stock_dto.exchange
    context.get_rt_flow()
    context.get_rt_price()
    context.get_day_k_new_n_dict(100)
    context.get_hundred_flow()

    # 触发均线
    result_trigger_list = monitor_result.select_size(context.code, 1, 5)
    content_arr_trigger = []
    if len(result_trigger_list) != 0:
        content_arr_trigger.append(
            json_util.to_json(result_trigger_list[0].get('monitor_result'))['content_arr'][0])
        for result_trigger in result_trigger_list:
            content_arr_trigger.append(json_util.to_json(result_trigger.get('monitor_result'))['content_arr'][1])

    # 资金流动
    content_arr_diagnosis = [['累计资金流动(日)', '五日', '十日', '二十日', '四十日', '六十日', '一百日'], ["主力净流入(亿)"]]
    main_io_sum = 0
    for i in range(len(context.hundred_flow)):
        main_io_sum += context.hundred_flow[i].get('main_io')
        if i == 4 or i == 9 or i == 19 or i == 39 or i == 59 or i == 99:
            content_arr_diagnosis[1].append(str(round(main_io_sum / 100000000, 2)) + '亿')

    # 机构参与度
    content_arr_diagnosis.append(['机构平均参与度(日)', '五日', '十日', '十五日', '二十日', '', ''])
    content_arr_diagnosis.append(['参与度百分比'])
    jgcyd_ave = 0
    for i in range(len(context.get_recently_jgcyd())):
        jgcyd_ave += context.recently_jgcyd[i]['JGCYD']
        if i == 4 or i == 9 or i == 14 or i == 19:
            content_arr_diagnosis[3].append(str(round(jgcyd_ave / (i + 1) * 100, 2)) + '%')

    # 最近6日流动详情
    di_content_arr = msg_service.trans_day_info(
        [StockDayInfoDto(context.code, context.name, date_util.get_date_str(),
                         context.rt_flow.main_i, context.rt_flow.main_o, context.rt_flow.main_io,
                         context.rt_flow.sb_i, context.rt_flow.sb_o, context.rt_flow.sb_io,
                         context.rt_flow.b_i, context.rt_flow.b_o, context.rt_flow.b_io,
                         context.rt_flow.m_i, context.rt_flow.m_o, context.rt_flow.m_io,
                         context.rt_flow.s_i, context.rt_flow.s_o, context.rt_flow.s_io,
                         context.rt_flow.turnover_rate, context.rt_flow.market_value, context.rt_flow.circulation_value,
                         'dfcfw')]
        + stock_day_info.select_new_n(context.code, 5))

    # 当前详情
    # 最新价格 + 均线价格 + 涨停价格 + 跌停价格 + 所属板块(含有跳转板块详情)
    context.get_day_k_new_n_dict(10)

    s_detail_info = [['最新价格', '开盘价格', '5均线价格', '10均线价格', '涨停价格',
                      '跌停价格', '基金持有数', '基金持有额', '基金流通比'],
                     [context.get_rt_price(), context.get_kp(), context.get_ave5(), context.get_ave10(),
                      context.get_harden(), context.get_drop(), len(context.get_fund_hold()),
                      context.get_fund_hold_amt(),
                      round(context.get_fund_hold_amt() / context.get_rt_flow().circulation_value / 100, 2)]]
    count = 1
    for sb in context.get_board_belong():
        s_detail_info[0].append('板块' + str(count))
        s_detail_info[1].append(html_util.get_form_hidden(
            '/rank/board/stock/mio', 'post', '板块内榜单',
            {'天数': {'value': str(5), 'name': 'days'},
             '板块编码': {'value': str(sb.get('board_code')), 'name': 'boardcode'}},
            str(sb.get('board_one'))))
        count += 1

    # 最新详情
    result += html_util.get_title("最新详情")
    result += html_util.get_a_table(s_detail_info)
    # 最近6日流动详情
    result += html_util.get_title("最近6日流动详情")
    result += html_util.get_a_table(di_content_arr)
    # 训练模型
    result += train_module_plus(context)
    # 资金流动
    result += html_util.get_title("资金流动")
    result += html_util.get_a_table(content_arr_diagnosis) + '<br>'
    # 新任务触发情况
    result += html_util.get_title("新任务触发情况")
    result += html_util.get_a_table(
        deal_task_c_msg(monitor_result.select_size_new(context.code, MonitorType.four, 5), False))
    # 触发均线
    result += html_util.get_title("触发均线任务")
    result += html_util.get_a_table(content_arr_trigger)
    # 折线图
    result += html_util.get_title("折线图")
    result += get_stock_broken_line_plus(context, 5) + '<br>'

    return result


# 训练模型
def train_module_plus(context: CommonContext):
    champion_max_inv = context.get_train_model().get('champion_max_inv')
    bd = champion_max_inv.split(':')[0]
    sd = champion_max_inv.split(':')[1]
    # 训练模型
    html = html_util.get_title('训练模型')
    best_module = html_util.get_form_hidden(
        '/train/module', 'post', '训练模型详情',
        {'股票编码': {'value': context.code, 'name': 'stockcode'},
         '股票名称': {'value': context.name, 'name': 'stockname'},
         '买入天数': {'value': str(bd), 'name': 'buyDays'},
         '卖出天数': {'value': str(sd), 'name': 'sellDays'}},
        champion_max_inv + '详情')
    statistical_module = html_util.get_form_hidden(
        '/train/module', 'post', '训练模型详情',
        {'股票编码': {'value': context.code, 'name': 'stockcode'},
         '股票名称': {'value': context.name, 'name': 'stockname'},
         '买入天数': {'value': str(context.get_train_model().get('buy_jfg')), 'name': 'buyDays'},
         '卖出天数': {'value': str(context.get_train_model().get('sel_jfg')), 'name': 'sellDays'}},
        str(context.get_train_model().get('buy_jfg')) + '买;' + str(context.get_train_model().get('sel_jfg')) + '卖')
    train_m_arr = [['最佳模式', '统计模式', '最高盈利', '起始价格', '结束价格', '价格涨幅', '最差模式'],
                   [best_module, statistical_module,
                    str(round((context.get_train_model().get('champion_max') - 100000) / 1000, 2)) + '%',
                    context.get_train_model().get('beg_price'), context.get_train_model().get('end_price'),
                    str(round((context.get_train_model().get('end_price') - context.get_train_model().get(
                        'beg_price')) / context.get_train_model().get('beg_price') * 100, 2)) + '%',
                    context.get_train_model().get('champion_min_itv')]]
    html += html_util.get_a_table(train_m_arr)
    return html


# 月线验证
def month_validation(date):
    s_dict = data_service.new_stock_all()
    result_path = os.path.join(config.data_path, 'result', '月macd', date, '历史验证')
    count = 0
    while (not os.path.exists(result_path)) or count > 4:
        count += 1
        date = date_util.add_day_str(date, -1)
        result_path = os.path.join(config.data_path, 'result', '月macd', date, '历史验证')
    s_list = []
    if not os.path.exists(result_path):
        for code in s_dict:
            s_list.append(s_dict[code])
        month_macd_service.month_macd_valid(s_list, date)
    excel_arr = excel_util.get_excel_info(os.path.join(result_path, '000000.xlsx'), '')
    checkout_dict = doc_util.get_a_doc_dict(os.path.join(result_path, '999999'), 'code')
    if (len(excel_arr) - 1) != len(s_dict.keys()):
        file_name_dict = {}
        for i in range(1, len(excel_arr)):
            file_name_dict[excel_arr[i][0]] = 1
        for code in s_dict:
            if code not in file_name_dict.keys() and code not in checkout_dict.keys():
                s_list.append(s_dict[code])
        month_macd_service.month_macd_valid(s_list, date)
    path = os.path.join(result_path, '000000.xlsx')
    path = path.replace('\\', '*').replace('/', '*')
    file_url = 'http://' + config.domain + '/download/doc/' + path
    return html_util.get_button_href(file_url, '点击下载验证结果')


# 获取指定日期的结果
def trigger_result(date):
    path = os.path.join(config.data_path, 'task', 'document', '突破均线', 'stock_monitor_dict')
    monitor_dict = doc_util.get_a_doc_dict(path, 'code')
    file_dict = {}
    up_flag = 0
    for code in monitor_dict.keys():
        monitor_info = json_util.info_to_json(monitor_dict[code])
        code = monitor_info['code']
        name = monitor_info['name']
        if 'trigger_time' not in monitor_info.keys():
            continue
        trigger_time = monitor_info['trigger_time']
        if trigger_time[0:10] != date_util.get_date_str():
            continue
        result_file_path = monitor_info['result_file_path']
        if 'score_info' not in monitor_info:
            up_flag = 1
        else:
            score_info = monitor_info['score_info']
            if 'exam_time' in score_info.keys():
                exam_time = score_info['exam_time']
                if (date_util.get_timestamp_now() - exam_time) > 600:
                    up_flag = 1
            else:
                up_flag = 1
        if up_flag == 1:
            monitor_info = score_service.common_exam(monitor_info)
            monitor_dict[code] = monitor_info
        score_info = json_util.info_to_json(monitor_info['score_info'])
        level = score_info['level']
        if 'trigger_time' not in monitor_info.keys():
            monitor_info['trigger_time'] = '2000-01-01 00:00:00'
            monitor_info['trigger_timestamp'] = date_util.datetime2timestamp('2000-01-01 00:00:00')
        trigger_time = monitor_info['trigger_time']  # 触发时间
        result_file_path = '当前' + result_file_path
        if result_file_path not in file_dict.keys():
            file_dict[result_file_path] = []
        file_list = []
        file_name = name + ':' + code + '--触发时间:' + trigger_time[0:10] + '--等级:' + level
        file_url = 'http://' + config.domain + '/download/position/' + date + '/' + result_file_path + '*' + file_name
        file_list.append(file_name)
        file_list.append(file_url)
        file_dict[result_file_path].append(file_list)
    if up_flag:
        doc_util.gen_a_doc(os.path.join(config.data_path, 'task', 'document', '突破均线'), 'stock_monitor_dict',
                           monitor_dict)
    return html_util.get_form_list_actual('仓位情况' + date, file_dict)


# 获取指定日期的结果
def position_result(user_code, date):
    path = os.path.join(config.data_path, 'task', 'document', '突破均线', 'stock_monitor_dict')
    monitor_dict = doc_util.get_a_doc_dict(path, 'code')
    file_dict = {}
    up_flag = 0
    user_m_dict = monitor_dict
    if user_code != '':
        if os.path.exists(os.path.join(users_path, user_code)):
            user_m_dict = doc_util.get_a_doc_dict(os.path.join(users_path, user_code), 'code')
    for code in monitor_dict.keys():
        if code not in user_m_dict.keys():
            continue
        monitor_info = json_util.info_to_json(monitor_dict[code])
        code = monitor_info['code']
        name = monitor_info['name']
        result_file_path = monitor_info['result_file_path']
        if 'score_info' not in monitor_info:
            up_flag = 1
        else:
            score_info = monitor_info['score_info']
            if 'exam_time' in score_info.keys():
                exam_time = score_info['exam_time']
                if (date_util.get_timestamp_now() - exam_time) > 600:
                    up_flag = 1
            else:
                up_flag = 1
        if up_flag == 1:
            monitor_info = score_service.common_exam(monitor_info)
            monitor_dict[code] = monitor_info
        score_info = json_util.info_to_json(monitor_info['score_info'])
        level = score_info['level']
        if 'trigger_time' not in monitor_info.keys():
            monitor_info['trigger_time'] = '2000-01-01 00:00:00'
            monitor_info['trigger_timestamp'] = date_util.datetime2timestamp('2000-01-01 00:00:00')
        trigger_time = monitor_info['trigger_time']  # 触发时间
        result_file_path = '当前' + result_file_path
        if result_file_path not in file_dict.keys():
            file_dict[result_file_path] = []
        file_list = []
        file_name = name + ':' + code + '--触发时间:' + trigger_time[0:10] + '--等级:' + level
        file_url = 'http://' + config.domain + '/download/position/' + date + '/' + result_file_path + '*' + file_name
        file_list.append(file_name)
        file_list.append(file_url)
        file_dict[result_file_path].append(file_list)
    if up_flag:
        doc_util.gen_a_doc(os.path.join(config.data_path, 'task', 'document', '突破均线'), 'stock_monitor_dict',
                           monitor_dict)
    return html_util.get_form_list_actual('仓位情况' + date, file_dict)


# 获取指定日期的结果
def month_cross_result(user_code, date):
    result_path = os.path.join(config.data_path, 'result', '月macd', date, '跑批结果')
    count = 0
    while not os.path.exists(result_path):
        count += 1
        if count > 30:
            return "最近无记录"
        date = date_util.add_day_str(date, -1)
        result_path = os.path.join(config.data_path, 'result', '月macd', date, '跑批结果')
    corr = excel_util.get_excel_info(os.path.join(result_path, '月macd跑批.xlsx'), '')
    return html_util.get_a_table(corr)


# 获取股票最近触发情况
def get_trigger_info(date, code):
    log_list = doc_util.get_doc_str_list(os.path.join(trigger_logs_path, 'out.log'))
    content_arr = []
    for log in log_list:
        if log[0:15] != 'triggerthedeal:':
            continue
        stock_info = json_util.info_to_json(log.split('triggerthedeal:')[1])
        if stock_info['code'] == code:
            name = stock_info['name']
            trigger_time = '2000-01-01'
            if 'trigger_time' in stock_info.keys():
                trigger_time = stock_info['trigger_time']
            # 展示今年的
            if date_util.date_to_timestamp(trigger_time[0:10]) < 1613836800:
                continue
            deal_price = 0
            if 'deal_price' in stock_info.keys():
                deal_price = str(stock_info['deal_price'])
            result_file_path = '未触发'
            if 'result_file_path' in stock_info.keys():
                result_file_path = stock_info['result_file_path']
            sb_io = '未记录'
            b_io = '未记录'
            hsl = '未记录'
            if 'sb_io' in stock_info.keys():
                sb_io = str(round(stock_info['sb_io'] / 10000)) + '万'
                b_io = str(round(stock_info['b_io'] / 10000)) + '万'
                hsl = str(stock_info['hsl'])
            score_level = '未分级'
            if 'score_info' in stock_info.keys():
                score_info = json_util.info_to_json(stock_info['score_info'])
                score_level = score_info['level']
            data = []
            data.append(code)
            data.append(name)
            data.append(trigger_time[0:10])
            data.append(trigger_time)
            data.append(deal_price)
            data.append(str(stock_info['ave5']))
            data.append(str(stock_info['ave10']))
            data.append(result_file_path)
            data.append(stock_info['macd'])
            data.append(sb_io)
            data.append(b_io)
            data.append(hsl)
            data.append(score_level)
            content_arr.append(data)
    content_arr.append(['编码', '名称', '日期', '触发时间', '当前价格', '五日均线', '十日均线',
                        '触发标志', 'MACD', '超大单净流入', '大单净流入', '换手率', '评分等级'])
    content_arr.reverse()
    return html_util.get_a_table(content_arr)


# 获取路径下所有文档
def file_path_names(path):
    return format_result2(path, '/download/doc/', '文档情况')


# 格式化整理2
def format_result2(path, down_url, title):
    file_list = doc_util.get_file_path_names(path)
    file_dict = {}
    for file_path_name in file_list:
        download_path = file_path_name.replace('\\', '*')
        file_path_name = file_path_name.split(path + '\\')[1]
        file_down_url = 'http://' + config.domain + down_url + '/' + download_path
        names = file_path_name.split('\\')
        names[-1] = {'url': file_down_url, 'name': names[-1]}
        if len(names) == 1:
            names = ['当前文档内容'] + names
        file_dict = dg_dict(file_dict, names)
    return html_util.get_form_list_actual(title, file_dict)


# 递归dictionary
# file_dict={'path1':{'path11':{path111':[],'path112':[]},'path12':{}},'path2':{}}
# name = [path1,path11,path111,{}]
def dg_dict(file_dict, names):
    names_len = len(names)
    for i in range(names_len):
        if isinstance(names[i], dict):
            file_dict.append(names[i])
            return file_dict
        else:
            name = names[i]
            if name not in file_dict.keys():
                if i == names_len - 2:
                    file_dict[name] = []
                else:
                    file_dict[name] = {}
            file_dict[name] = dg_dict(file_dict[name], names[1:names_len])
            return file_dict


# macd + ave 跑批历史数据验证
def record_validation(stock_code, size):
    # 按照季度拆分
    log_list = doc_util.get_doc_str_list(os.path.join(trigger_logs_path, 'out.log'))
    record_dict = {}
    stock_name = data_service.stock(stock_code)['name']
    for log in log_list:
        if log[0:15] != 'triggerthedeal:':
            continue
        stock_info = json_util.info_to_json(log.split('triggerthedeal:')[1])
        code = stock_info['code']
        if code not in record_dict.keys():
            record_dict[code] = []
        record_dict[code].append(stock_info)
    for code in record_dict.keys():
        content_arr = []
        capital_hold = 0  # 持仓资金
        capital_idle = 100000  # 闲置资金
        hand_hold = 0  # 闲置资金
        last_deal_date = ''
        name = data_service.stock(code)['name']
        # path = os.path.join(result_path, date_util.get_date_str(), '记录认证', name + '-' + code + '.xlsx')
        # if os.path.exists(path):
        #     continue
        content_arr.append(['编码', '名称', '日期', '触发时间', '当前价格', '五日均线', '十日均线',
                            '触发标志', 'MACD', '超大单净流入', '大单净流入', '换手率', '持有手数', '持仓金额',
                            '闲置金额', '总金额'])
        s_log_list = record_dict[code]
        for stock_info in s_log_list:
            if stock_info['code'] == code:
                deal_price = stock_info['rt_price']  # 当前价格
                deal_time = stock_info['deal_time']  # 交易时间
                deal_date = deal_time[0:10]  # 交易日期
                if deal_date == last_deal_date:
                    print('同一天多次触发')
                    continue
                last_deal_date = deal_date
                # 交易标志 deal_flag = 0  # 1:加仓 2:入仓 3:清仓 4:减仓
                deal_flag = 0
                if 'deal_flag' in stock_info.keys():
                    deal_flag = stock_info['deal_flag']
                buy_sell_flag = 0
                # buy_sell_flag = 0  # 1买入 -1卖出
                # 交易标志 deal_flag = 0  # 1:全仓 2:加半仓 3:清仓 4:减半仓
                if deal_flag == 1 or deal_flag == 2:  # 买入
                    buy_sell_flag = 1
                    deal_capital = capital_idle
                    if hand_hold == 0 and deal_flag == 2:
                        deal_capital = int(deal_capital / 2)
                    deal_hand = int(deal_capital / (deal_price * 100))
                    if deal_hand == 0:  # 如果可购买数量为0 返回结果
                        continue
                elif deal_flag == 3 or deal_flag == 4:  # 卖出
                    buy_sell_flag = -1
                    if hand_hold != 0:
                        deal_hand = int(capital_idle / (deal_price * 100))
                        if deal_hand == 0 and deal_flag == 4:  # 全仓状态
                            deal_hand = int(hand_hold / 2)
                        else:  # 清仓
                            deal_hand = hand_hold
                    else:
                        continue
                else:
                    continue
                hand_hold = hand_hold + deal_hand * buy_sell_flag
                deal_amt = round(deal_hand * deal_price * 100, 2)  # 成交金额
                deal_tax = round(deal_amt * 0.00025, 2)  # 印花税
                capital_hold = round(hand_hold * deal_price * 100, 2)
                capital_idle = round(capital_idle - deal_amt * buy_sell_flag - deal_tax, 2)
                data = []
                data.append(code)
                data.append(name)
                data.append(deal_date)
                data.append(deal_time)
                data.append(deal_price)
                data.append(str(stock_info['ave5']))
                data.append(str(stock_info['ave10']))
                if 'result_file_path' not in stock_info.keys():
                    data.append('未归类')
                else:
                    data.append(stock_info['result_file_path'])
                data.append(stock_info['macd'])
                if 'sb_io' in stock_info.keys():
                    data.append(str(stock_info['sb_io']))
                    data.append(str(stock_info['b_io']))
                    data.append(str(stock_info['hsl']))
                else:
                    data.append('无记录')
                    data.append('无记录')
                    data.append('无记录')
                data.append(str(hand_hold))
                data.append(str(capital_hold))
                data.append(str(capital_idle))
                data.append(str(round(capital_hold + capital_idle, 2)))
                content_arr.append(data)
        excel_util.gen_an_excel(os.path.join(result_path, date_util.get_date_str(), '记录认证'), name + '-' + code, '',
                                content_arr)
    path = os.path.join(result_path, date_util.get_date_str(), '记录认证', stock_name + '-' + stock_code + '.xlsx')
    path = path.replace('\\', '*').replace('/', '*')
    file_url = 'http://' + config.domain + '/download/doc/' + path
    return html_util.get_button_href(file_url, '点击下载验证结果')


# 汇总验证结果
# content_arr.append(['编码', '名称', '日期', '触发时间', '当前价格', '五日均线', '十日均线',
#                             '触发标志', 'MACD', '超大单净流入', '大单净流入', '换手率', '持有手数', '持仓金额',
#                             '闲置金额', '总金额'])

# ['0编码', '1名称', '2日期', '3触发时间', '4当前价格', '5五日均线', '6十日均线',
#  '7触发标志', '8MACD', '9超大单净流入', '10大单净流入', '11换手率', '12持有手数',
#  '13持仓金额', '14闲置金额', '15总金额'])
def conclusion_record_validation():
    valid_path = os.path.join(result_path, date_util.get_date_str(), '记录认证')
    path_names = doc_util.get_file_names(valid_path)
    result_data = [['编码', '名称', '当前价格', '最高资金', '最低资金', '最高涨幅',
                    '最低涨幅', '价格涨幅', '资金涨幅', '最终资金', '最终利润']]
    for path_name in path_names:
        if path_name == '000000':
            continue
        content_arr = excel_util.get_excel_info(os.path.join(valid_path, path_name + '.xlsx'), '')
        rows_num = len(content_arr)
        if rows_num == 1: continue
        code = content_arr[1][0]
        name = content_arr[1][1]
        beg_price = content_arr[1][4]
        max_capital = 0
        min_capital = 99999999
        end_capital = 0
        rt_price = price_util.get_rt_p(code)
        for i in range(1, rows_num):
            row = content_arr[i]
            hand = int(row[12])
            idle_capital = float(row[14])
            all_capital = float(row[15])
            if i == rows_num - 1:
                all_capital = idle_capital + hand * rt_price * 100
                end_capital = all_capital
            if max_capital < all_capital:
                max_capital = all_capital
            if min_capital > all_capital:
                min_capital = all_capital
        data = []
        data.append(code)
        data.append(name)
        data.append(str(rt_price))
        data.append(str(max_capital))
        data.append(str(min_capital))
        data.append(str(round((max_capital - 100000) / 1000, 2)))
        data.append(str(round((min_capital - 100000) / 1000, 2)))
        data.append(str(round((rt_price - beg_price) / beg_price * 100, 2)))
        data.append(str(round((end_capital - 100000) / 1000, 2)))
        data.append(str(round(end_capital, 2)))
        data.append(str(round(end_capital - 100000, 2)))
        result_data.append(data)
    excel_util.gen_an_excel(valid_path, '000000', '', result_data)


# 涨幅榜
def rank_zfb(query_date):
    result = ''
    content_arr = parse_util.list_to_arr(stock_day_k.select_rank_zf(query_date), ['code', 'name', 'zf'])
    # zfb
    result += html_util.get_title("涨幅榜")
    result += html_util.get_a_table(content_arr) + '<br>'
    return result


# 市值榜
def rank_szb():
    content_arr = parse_util.list_to_arr(stock_info.select_order_sz(),
                                         ['code', 'name', 'total_val'])
    result = html_util.get_title("涨幅榜")
    result += html_util.get_a_table(content_arr) + '<br>'
    return result


# 板块内榜单
# val : 市值 0:无操作(按照资金流排序) 1:按照市值排序 2:按照振幅排序
# days : 统计天数 0:当前天实时资金流
# board_code : 板块编码
def rank_board_stock_mio_plus(val, days, board_code):
    s_list = boards_info.select_board_detail(board_code)
    if len(s_list) == 0:
        return '板块不存在'
    if days == 0:  # 查询实时资金
        s_list = caiptal_util.stock_flow_info(s_list)
        content_arr = []
        for stock in s_list:
            # 重新构建 content_arr
            content_arr.append(['', stock.get('code'), stock.get('name'), stock.get('total_val'), 0, 0,
                                round(stock.get('main_io') / 100000000, 2),
                                round(stock.get('main_io') / 1000000 / stock.get('total_val'), 4)])
        content_arr = sorted(content_arr, key=lambda x: (x[6]), reverse=True)
    else:
        content_arr = rank_mio_task(False)
        content_arr = sorted(content_arr, key=lambda x: (x[(days - 1) * 2 + 7]), reverse=True)
    if val == 1:  # 按照市值排序
        content_arr = sorted(content_arr, key=lambda x: (x[3]), reverse=True)
    elif val == 2:  # 按照振幅排序
        content_arr = sorted(content_arr, key=lambda x: (x[(days - 1) * 2 + 8]), reverse=True)
    bs_list = parse_util.list_dict_to_list(s_list, 'code')
    content_arr_board = []
    for i in range(len(content_arr)):
        content = content_arr[i]
        content[0] = i + 1
        if content[1] not in bs_list:
            continue
        content[1] = html_util.get_form_hidden(
            '/diagnosis/stock', 'post', '一键诊断',
            {'编码': {'value': content[1], 'name': 'stockcode'}, '名称': {'value': '', 'name': 'stockname'}},
            content[1] + '详情')
        content[4] = days
        content[5] = content[(days - 1) * 2 + 7]
        content[6] = content[(days - 1) * 2 + 8]
        content_arr_board.append(content[0:7])
    result = html_util.get_title("板块内榜单")
    result += html_util.get_form_has_value('/rank/board/stock/mio', 'post', '资金流入榜',
                                           {'天数': {'value': str(days), 'name': 'days'},
                                            '板块编码': {'value': board_code, 'name': 'boardcode'}}, '点击查询')
    result += html_util.get_page_index('/rank/board/stock/mio',
                                       {'天数': {'value': str(days), 'name': 'days'},
                                        '市值': {'value': str(val), 'name': 'val'},
                                        '板块': {'value': board_code, 'name': 'boardcode'}},
                                       '天数', [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10], days)

    button_val = html_util.get_form_hidden_blank('/rank/board/stock/mio',
                                                 {'天数': {'value': str(days), 'name': 'days','type':'hidden'},
                                                  '市值': {'value': str(1), 'name': 'val','type':'hidden'},
                                                  '板块': {'value': board_code, 'name': 'boardcode'}},
                                                 '市值', 0)
    button_io = html_util.get_form_hidden_blank('/rank/board/stock/mio',
                                                {'天数': {'value': str(days), 'name': 'days','type':'hidden'},
                                                 '资金': {'value': str(0), 'name': 'val','type':'hidden'},
                                                 '板块': {'value': board_code, 'name': 'boardcode'}},
                                                '主力净流入(亿)', 0)
    button_fd = html_util.get_form_hidden_blank('/rank/board/stock/mio',
                                                {'天数': {'value': str(days), 'name': 'days','type':'hidden'},
                                                 '幅度': {'value': str(2), 'name': 'val','type':'hidden'},
                                                 '板块': {'value': board_code, 'name': 'boardcode'}},
                                                '流入幅度(万分)', 0)
    result += html_util.get_a_table(
        [['排名', '编码', '名称', button_val, '计算天数', button_io, button_fd]] + content_arr_board) + '<br>'
    return result


# 资金流入榜
# num 0:资金 1:幅度
# return:  ['序号', stock.get('code'), stock.get('name'), stock.get('total_val'), 0, '', '']
def rank_mio_task(update: bool):
    key = 'rank_mio_task'
    content_arr = json_util.to_json(cache_util.get_doc_expire(key))
    if not content_arr or update:
        content_arr = []
        s_list = stock_info.selectall()
        for stock in s_list:
            if stock['total_val'] <= 10:
                continue
            di_list = stock_day_info.select_size(stock.get('code'), 10)
            di_len = len(di_list)
            if len(di_list) == 0:
                continue
            # 三个空的补位
            flow_list = ['', stock.get('code'), stock.get('name'), stock.get('total_val'), 0, '', '']
            total_main_io = 0
            for i in range(10):
                if di_len > i:
                    total_main_io += di_list[i].get('main_io')
                flow_list.append(round(total_main_io / 100000000, 2))
                flow_list.append(round(total_main_io / stock.get('total_val') / 1000000, 4))
            content_arr.append(flow_list)
        cache_util.set_doc_expire(key, str(content_arr), 25 * 60)  # 有效期25小时
    return content_arr


# 资金流入榜
# num 0:资金 1:幅度
def rank_mio(days, num):
    content_arr = rank_mio_task(False)
    content_arr = sorted(content_arr, key=lambda x: (x[days + num + 6]), reverse=True)
    content_arr = sorted(content_arr, key=lambda x: (x[(days - 1) * 2 + 7 + num]), reverse=True)
    for i in range(len(content_arr)):
        content = content_arr[i]
        content[0] = i + 1
        content[1] = html_util.get_form_hidden(
            '/diagnosis/stock', 'post', '一键诊断',
            {'编码': {'value': content[1], 'name': 'stockcode'}, '名称': {'value': '', 'name': 'stockname'}},
            content[1] + '详情')
        content[5] = content[(days - 1) * 2 + 7]
        content[6] = content[(days - 1) * 2 + 8]
        content_arr[i] = content[0:7]
    result = html_util.get_title("资金流入榜")
    if num == 0:
        url = '/rank/mio'
    else:
        url = '/rank/mio/fd'
    result += html_util.get_form_has_value(url, 'post', '资金流入榜',
                                           {'天数': {'value': str(days), 'name': 'days'}}, '点击查询')
    result += html_util.get_a_table(
        [['排名', '编码', '名称', '市值', '计算天数', '主力净流入(亿)', '流入幅度(万分)']] + content_arr) + '<br>'
    return result


# 板块资金流入榜
def rank_board_mio(days):
    content_arr = sorted(concat_board_rt_info(days), key=lambda x: (x[days + 3]))
    content_arr.reverse()
    result = html_util.get_title("板块资金流入榜")
    result += html_util.get_form_has_value('/rank/board/mio', 'post', '板块资金流入榜',
                                           {'天数': {'value': str(days), 'name': 'days'}}, '点击查询')
    common_button = html_util.get_form_hidden_blank(
        '/rank/board/mio', {'天数': {'value': '@@@@@@', 'name': 'days', 'type': 'hidden'}}, '######', 0)
    result += html_util.get_a_table(
        [['板块编码', '板块名称',
          common_button.replace('@@@@@@', '-1').replace('######', '实时涨幅'),
          common_button.replace('@@@@@@', '0').replace('######', '实时资金'),
          common_button.replace('@@@@@@', '1').replace('######', '(一)'),
          common_button.replace('@@@@@@', '2').replace('######', '(二)'),
          common_button.replace('@@@@@@', '3').replace('######', '(三)'),
          common_button.replace('@@@@@@', '4').replace('######', '(四)'),
          common_button.replace('@@@@@@', '5').replace('######', '(五)'),
          common_button.replace('@@@@@@', '6').replace('######', '(六)'),
          common_button.replace('@@@@@@', '7').replace('######', '(七)'),
          common_button.replace('@@@@@@', '8').replace('######', '(八)'),
          common_button.replace('@@@@@@', '9').replace('######', '(九)'),
          common_button.replace('@@@@@@', '10').replace('######', '(十)')]]
        + content_arr) + '<br>'
    return result


# 准备板块排行数据
def board_info_task(update: bool):
    key = 'rank_board_mio'
    content_arr = json_util.to_json(cache_util.get_doc_expire(key))
    if not content_arr or update:
        content_arr = []
        board_list = boards_info.select_all_board_code()
        for board_code in board_list:
            try:
                board_detail = boards_info.select_board_detail(board_code)
                board_flow_info = [board_code, board_detail[0].get('board_one'), '', '']
                board_io_list = []
                for s_detail in board_detail:
                    s_info = json_util.to_json(s_detail.get('stock_info'))
                    if s_info and 'main_io_list' in s_info.keys():
                        board_io_list.append(s_info.get('main_io_list'))
                row = len(board_io_list)
                total_main_io = 0
                for i in range(10):
                    for j in range(row):
                        if board_io_list[j][i]:
                            total_main_io += board_io_list[j][i]
                    board_flow_info.append(round(total_main_io / 100000000, 2))
                content_arr.append(board_flow_info)
            except:
                print('error 异常')
        cache_util.set_doc_expire(key, str(content_arr), 60 * 25)
    return content_arr


# 板块实时信息
def concat_board_rt_info(days):
    content_arr = board_info_task(False)
    boards_info_dict = caiptal_util.board_flow_info()
    for i in range(len(content_arr)):
        content_list = content_arr[i]
        rt_main_io = dict_util.get_default(boards_info_dict, content_list[0], {})
        if type(rt_main_io) is str:
            rt_main_io = {}
        content_list[2] = dict_util.get_default(rt_main_io, 'zf', 0)
        content_list[3] = round(dict_util.get_default(rt_main_io, 'main_io', 0) / 100000000, 2)
        detail_button = html_util.get_form_hidden(
            '/rank/board/stock/mio', 'post', '板块内榜单',
            {'天数': {'value': str(days), 'name': 'days'}, '编码': {'value': str(content_list[0]), 'name': 'boardcode'}},
            str(content_list[0]) + '详情')
        content_list[0] = detail_button
        content_arr[i] = content_list
    return content_arr


# 资金折线图
def get_stock_broken_line_plus(context: CommonContext, days):
    row_dict = {'股票编码': {'value': context.code, 'name': 'stockcode'},
                '股票名称': {'value': context.name, 'name': 'stockname'},
                '累计天数': {'value': str(days), 'name': 'days'}}
    result = html_util.get_form_has_value('/flow/broken/line', 'post', '监控代码', row_dict, '查看详情')
    # 大资金折线图
    main_100 = context.get_hundred_flow()[0:100]
    sp_100 = context.get_day_k_new_n_dict(100)

    max_sp = max(sp_100, key=lambda x: x['sp']).get('sp')
    min_sp = min(sp_100, key=lambda x: x['sp']).get('sp')
    max_main = max(main_100, key=lambda x: x['main_io']).get('main_io')
    min_main = min(main_100, key=lambda x: x['main_io']).get('main_io')
    bs = round((max_main - min_main) / (max_sp - min_sp))
    main_100.reverse()
    sp_100.reverse()
    x0 = []
    x1 = []
    x2 = []
    y0 = []
    y1 = []
    y2 = []
    v0 = []
    v1 = []
    v2 = []
    five_total = 0
    for i in range(len(main_100)):
        five_total += float(main_100[i].get('main_io'))
        y0.append(min_sp)
        x0.append(i + 1)
        if i % 5 == 0:
            v0.append(main_100[i].get('rq')[-5:])
        else:
            v0.append('')
        if (i + 1) % days == 0:
            x1.append(i + 1)
            y1.append(round(five_total / bs + min_sp, 2))
            v1.append(str(round(five_total / 100000000, 2)) + '亿')
            five_total = 0
        if (i + 1) % 1 == 0:
            x2.append(i + 1)
            y2.append(sp_100[i].get('sp'))
            if i % 5 == 0:
                v2.append(main_100[i].get('sp'))
            else:
                v2.append('')
    result += chart_service.get_broken_line('flow_broken_line', [x0, x2, x1], [y0, y2, y1], [v0, v2, v1])
    return result


# 资金折线图
def get_stock_broken_line(s_code, s_name, days):
    stock_dto = get_by_name_or_code(s_code, s_name)
    context = CommonContext(stock_dto.code)
    context.name = stock_dto.name
    return get_stock_broken_line_plus(context, days)


# 训练模型
def train_module(code: str, name: str, tm_info) -> str:
    champion_max_inv = tm_info.get('champion_max_inv')
    bd = champion_max_inv.split(':')[0]
    sd = champion_max_inv.split(':')[1]

    # 训练模型
    html = html_util.get_title('训练模型')
    best_module = html_util.get_form_hidden(
        '/train/module', 'post', '训练模型详情',
        {'股票编码': {'value': code, 'name': 'stockcode'},
         '股票名称': {'value': name, 'name': 'stockname'},
         '买入天数': {'value': str(bd), 'name': 'buyDays'},
         '卖出天数': {'value': str(sd), 'name': 'sellDays'}},
        champion_max_inv + '详情')
    statistical_module = html_util.get_form_hidden(
        '/train/module', 'post', '训练模型详情',
        {'股票编码': {'value': code, 'name': 'stockcode'},
         '股票名称': {'value': name, 'name': 'stockname'},
         '买入天数': {'value': str(tm_info.get('buy_jfg')), 'name': 'buyDays'},
         '卖出天数': {'value': str(tm_info.get('sel_jfg')), 'name': 'sellDays'}},
        str(tm_info.get('buy_jfg')) + '买;' + str(tm_info.get('sel_jfg')) + '卖')
    train_m_arr = [['最佳模式', '统计模式', '最高盈利', '起始价格', '结束价格', '价格涨幅', '最差模式'],
                   [best_module, statistical_module, str(round((tm_info['champion_max'] - 100000) / 1000, 2)) + '%',
                    tm_info['beg_price'], tm_info['end_price'],
                    str(round((tm_info['end_price'] - tm_info['beg_price']) / tm_info['beg_price'] * 100, 2)) + '%',
                    tm_info['champion_min_itv']]]
    html += html_util.get_a_table(train_m_arr)
    return html


# 训练模型
def train_module_detail(code: str, name, bd: str, sd: str) -> str:
    s_info = {}
    if code != '':
        s_info = stock_info.selectone(code)
    elif name != '':
        s_info = stock_info.select_name_like(name)[0]
        code = s_info.get('code')
    tm_info = training_model.train(code)
    champion_max_inv = tm_info.get('champion_max_inv')
    if bd == '' or sd == '':
        bd = champion_max_inv.split(':')[0]
        sd = champion_max_inv.split(':')[1]
    else:
        bd = int(bd)
        sd = int(sd)
    row_dict = {'股票编码': {'value': code, 'name': 'stockcode'},
                '股票名称': {'value': name, 'name': 'stockname'},
                '买入天数': {'value': str(bd), 'name': 'buyDays'},
                '卖出天数': {'value': str(sd), 'name': 'sellDays'}}
    html = html_util.get_form_has_value('/train/module', 'post', '监控代码', row_dict, '查看详情')

    html += train_module(code, s_info.get('name'), tm_info)

    flow_sum_dict = tm_info['flow_sum_dict']
    flow_info = caiptal_util.get_flow(code)
    if tm_info.get('end_rq') == date_util.get_date_str():
        flow_info.main_io = 0
    html += html_util.get_title('最新资金')
    new_capital_arr = [[], []]
    for i in range(1, 15):
        new_capital_arr[0].append(str(i + 1) + '日金额')
        new_capital_arr[1].append(str(round((flow_sum_dict.get(i) + flow_info.main_io) / 100000000, 2)) + '亿')
    html += html_util.get_a_table(new_capital_arr)

    amt_sum_sort = tm_info['amt_sum_sort']
    sort_row_zero = ['收益前十']
    sort_row_one = ['收益']
    sort_row_two = ['收益倒十']
    sort_row_thr = ['收益']
    for i in range(10):
        sort_row_zero.append(amt_sum_sort[i].get('key'))
        sort_row_one.append(str(round((amt_sum_sort[i].get('amt') - 100000) / 1000, 2)) + '%')
    for i in range(10):
        sort_row_two.append(amt_sum_sort[len(amt_sum_sort) - i - 1].get('key'))
        sort_row_thr.append(str(round((amt_sum_sort[len(amt_sum_sort) - i - 1].get('amt') - 100000) / 1000, 2)) + '%')
    html += html_util.get_a_table([sort_row_zero, sort_row_one, sort_row_two, sort_row_thr])

    # 模型折线图
    modult_info = tm_info.get(str(bd) + ':' + str(sd))
    html += chart_service.get_broken_line('train_module',
                                          modult_info.get('broken_line_x'),
                                          modult_info.get('broken_line_y'),
                                          modult_info.get('broken_line_v'))
    return html


# 获取用户监控信息
def get_user_monitor(usercode: str):
    monitor_list = users_service.get_all_monitor(usercode)
    content_arr = [['序号', '编码', '名称', '删除', '持仓', '监控配置', '备注']]
    max_note = len(parse_util.str_to_list(dict_util.get_default(
        max(monitor_list, key=lambda x: len(parse_util.str_to_list(dict_util.get_default(x, 'note', [])))), 'note',
        [])))
    for i in range(len(monitor_list)):
        stock = monitor_list[i]
        row_info = [(i + 1)]
        row_info.append(html_util.get_form_hidden_blank(
            UrlSelf.zhenDuanXq.value,
            {'股票编码': {'value': stock['code'], 'name': 'stockcode', 'type': 'hidden'},
             '股票名称': {'value': stock['name'], 'name': 'stockname', 'type': 'hidden'}},
            stock['code'], 1))
        row_info.append(stock['name'])
        # 删除监控按钮
        row_info.append(html_util.get_form_hidden_blank(
            '/task1/del', {'用户编码': {'value': usercode, 'name': 'usercode', 'type': 'hidden'},
                           '股票编码': {'value': stock['code'], 'name': 'stockcode', 'type': 'hidden'}}, '删除监控', 0))
        # 更改持仓
        row_info.append(html_util.get_form_size(
            '/task1/hold/update',
            {'用户编码': {'value': usercode, 'name': 'usercode', 'type': 'hidden'},
             '股票编码': {'value': stock['code'], 'name': 'stockcode', 'type': 'hidden'},
             '持有': {'value': str(int(stock['total_hand'])), 'name': 'stockhold', 'type': 'text'}},
            '更改', 3))
        # 配置监控策略
        row_info.append(
            html_util.get_form_hidden(
                '/strategy/stock/monitor/config', 'post', '跳转策略配置',
                {'用户编码': {'value': usercode, 'name': 'usercode'},
                 '股票编码': {'value': stock['code'], 'name': 'stockcode'}}, '配置监控'))
        # 备注信息
        notes = parse_util.str_to_list(dict_util.get_default(stock, 'note', []))
        dict_note = {'用户编码': {'value': usercode, 'name': 'usercode', 'type': 'hidden'},
                     '股票编码': {'value': stock['code'], 'name': 'stockcode', 'type': 'hidden'},
                     '备注数量': {'value': str(max_note + 1), 'name': 'notenum', 'type': 'hidden'}}
        for num in range(len(notes)):
            dict_note['备注内容' + str(num)] = {'value': notes[num], 'name': 'stocknote' + str(num), 'type': 'text'}
        for num in range(len(notes), max_note + 1):
            dict_note['备注内容' + str(num)] = {'value': '', 'name': 'stocknote' + str(num), 'type': 'text'}
        row_info.append(html_util.get_form_size(
            '/stock/monitor/update/note', dict_note, '备注', 10))
        content_arr.append(row_info)
    html = html_util.get_title('用户监控信息')
    html += html_util.get_a_table(content_arr)
    return html


# 处理 task_c 结果数据
def deal_task_c_msg(task_c_trigger: List[MonitorResult], sort: bool):
    task_c_arr = [['编码', '名称', '时间', '价格', '买卖', '提示', '备注1', '备注2', '备注3']]
    monitor_list = []
    for task_c_info in task_c_trigger:
        monitor_dict = eval(
            task_c_info.monitor_result.replace('false', 'False').replace('true', 'True').replace('null', 'None'))
        monitor_list.append(monitor_dict)
    if sort:
        monitor_list = sorted(monitor_list, key=lambda x: x['bs'])
    for monitor_info in monitor_list:
        monitor_c = Monitor('', '')
        monitor_c.__dict__ = monitor_info
        if (monitor_c.break_ave5 or monitor_c.below_ave5
            or monitor_c.break_ave10 or monitor_c.below_ave10
            or monitor_c.main_io_sell or monitor_c.main_io_buy) \
                and monitor_c.prompt:
            task_c_row = []
            task_c_row.append(html_util.get_form_hidden(
                '/diagnosis/stock', 'post', '一键诊断',
                {'编码': {'value': monitor_c.code, 'name': 'stockcode'},
                 '名称': {'value': monitor_c.name, 'name': 'stockname'}}, "查看详情"))
            task_c_row.append(monitor_c.code)
            task_c_row.append(monitor_c.name)
            task_c_row.append(monitor_c.task_time)
            task_c_row.append(monitor_c.rt_price)
            if monitor_c.bs == 1:
                task_c_row.append('买入')
            if monitor_c.bs == 2:
                task_c_row.append('卖出')
            if monitor_c.break_ave5:
                task_c_row.append('突破五日均线')
            if monitor_c.break_ave10:
                task_c_row.append('突破十日均线')
            if monitor_c.below_ave5:
                task_c_row.append('跌破五日均线')
            if monitor_c.below_ave10:
                task_c_row.append('跌破十日均线')
            if monitor_c.main_io_sell:
                task_c_row.append('主力资金卖出')
                task_c_row.append(monitor_c.main_io_sell_model)
            if monitor_c.main_io_buy:
                task_c_row.append('主力资金买入')
                task_c_row.append(monitor_c.main_io_buy_model)
            task_c_arr.append(task_c_row)
    return task_c_arr


# 根据 code 或者 name 获取股票信息
def get_by_name_or_code(code: str, name: str):
    if name != '':
        return stock_info.select_by_name(name)[0]
    elif code != '':
        return stock_info.select_by_code(code)


# 获取指定日期的结果
def trigger_result_c(date):
    return html_util.get_a_table(
        deal_task_c_msg(monitor_result.select_with_date_type(date, MonitorType.four), True))


# 用户监控策略配置
def strategy_stock_monitor_config(usercode, stockcode, addtype):
    # 开盘 涨停 ...
    # rt_price = price_util.get_rt_p(stockcode)
    rt_price = 0
    msc_list = monitor_strategy_config.select_by_user_stock(usercode, stockcode)

    html_price_list = [html_util.get_title("设置价格")]
    html_ave_list = [html_util.get_title("设置均线")]
    html_io_list = [html_util.get_title("设置资金流")]
    html_macd_list = [html_util.get_title("设置MACD")]
    this_action = '/strategy/stock/monitor/config'
    update_action = '/strategy/conf/update'
    for msc in msc_list:
        strategy_code = msc.get(StrategyCons.strategy_code)
        if strategy_code[0:2] == '11':  # 获取 一个价格操作
            html_price_list.append(get_price_form(update_action, msc, stockcode, strategy_code, 0, 1) + \
                                   get_complete_button(update_action, stockcode, msc.get(StrategyCons.id)) + \
                                   get_abandon_button(update_action, stockcode, msc.get(StrategyCons.id)))
        if strategy_code[0:2] == '12':
            html_ave_list.append(get_ave_form(update_action, msc, stockcode, strategy_code, 1) + \
                                 get_complete_button(update_action, stockcode, msc.get(StrategyCons.id)) + \
                                 get_abandon_button(update_action, stockcode, msc.get(StrategyCons.id)))
        if strategy_code[0:2] == '13':
            html_io_list.append(get_io_form(update_action, msc, stockcode, strategy_code, 1) + \
                                get_complete_button(update_action, stockcode, msc.get(StrategyCons.id)) + \
                                get_abandon_button(update_action, stockcode, msc.get(StrategyCons.id)))
        if strategy_code[0:2] == '14':
            html_macd_list.append(get_macd_form(update_action, msc, stockcode, strategy_code, 1) + \
                                  get_complete_button(update_action, stockcode, msc.get(StrategyCons.id)) + \
                                  get_abandon_button(update_action, stockcode, msc.get(StrategyCons.id)))
    if len(html_price_list) == 1 or addtype == '11':
        html_price_list.append(
            get_price_form(update_action, {}, stockcode, str(1100 + len(html_price_list)), rt_price, 0))
    if len(html_ave_list) == 1 or addtype == '12':
        html_ave_list.append(get_ave_form(update_action, {}, stockcode, str(1200 + len(html_price_list)), 0))
    if len(html_io_list) == 1 or addtype == '13':
        html_io_list.append(get_io_form(update_action, {}, stockcode, str(1300 + len(html_price_list)), 0))
    if len(html_macd_list) == 1 or addtype == '14':
        html_macd_list.append(get_macd_form(update_action, {}, stockcode, str(1400 + len(html_price_list)), 0))
    html_price_list.append(get_add_button(this_action, stockcode, '11') + '<br>')
    html_ave_list.append(get_add_button(this_action, stockcode, '12') + '<br>')
    html_io_list.append(get_add_button(this_action, stockcode, '13') + '<br>')
    html_macd_list.append(get_add_button(this_action, stockcode, '14') + '<br>')
    html = html_util.get_title('设置' + stockcode + '监控配置') + '<br>'
    for h in html_price_list:
        html += h + '<br>'
    for h in html_ave_list:
        html += h + '<br>'
    for h in html_io_list:
        html += h + '<br>'
    for h in html_macd_list:
        html += h + '<br>'
    return html


# 获取增加按钮
def get_add_button(action, stockcode, addtype):
    add_button = {'增加类型': {'value': addtype, 'name': 'addtype', 'type': 'hidden'},
                  '股票编码': {'value': stockcode, 'name': 'stockcode', 'type': 'hidden'}}
    return html_util.get_form_config1(action, add_button, '+1', 0, 0, 1, 0, 1)


# 获取完成按钮
def get_complete_button(action, stockcode, strategyid):
    complete_button = {'策略序号': {'value': str(strategyid), 'name': 'strategyid', 'type': 'hidden'},
                       '按钮类型': {'value': '2', 'name': 'status', 'type': 'hidden'},
                       '股票编码': {'value': stockcode, 'name': 'stockcode', 'type': 'hidden'}}
    return html_util.get_form_config1(action, complete_button, '完成', 0, 0, 1, 0, 1)


# 获取放弃按钮
def get_abandon_button(action, stockcode, strategyid):
    abandon_button = {'策略序号': {'value': str(strategyid), 'name': 'strategyid', 'type': 'hidden'},
                      '按钮类型': {'value': '3', 'name': 'status', 'type': 'hidden'},
                      '股票编码': {'value': stockcode, 'name': 'stockcode', 'type': 'hidden'}}
    return html_util.get_form_config1(action, abandon_button, '放弃', 0, 0, 1, 0, 1)


# 获取价格配置表格
# default 0:使用默认参数 1:使用查询参数
def get_price_form(action, msc, stockcode, strategycode, price, default):
    # 买卖方式下拉选框
    bs_conf_op_list = copy.deepcopy(StrategyCons.op_list_bs_conf)
    type_conf_op_list = StrategyCons.op_list_price_conf
    strategyid = 0
    validdays = '100'
    promptinfo = '请输入触发提示的扩展信息'
    if default == 1:
        bs_conf_op_list = [parse_util.list_to_dict(bs_conf_op_list, 'value').get(msc.get(StrategyCons.bs_flag))]
        type_conf_op_list = [
            parse_util.list_to_dict(type_conf_op_list, 'value').get(msc.get(StrategyCons.conf_info)['pricetype'])]
        validdays = msc.get(StrategyCons.conf_info)['validdays']
        promptinfo = msc.get(StrategyCons.conf_info)['promptinfo']
        price = msc.get(StrategyCons.conf_info)['stockprice']
        strategyid = msc.get(StrategyCons.id)
    form = html_util.get_form_conf(
        action,
        {
            '策略序号': {
                'value': str(strategyid),
                'name': 'strategyid',
                'type': 'hidden'
            },
            '策略编码': {
                'value': strategycode,
                'name': 'strategycode',
                'type': 'hidden'
            },
            '股票编码': {
                'value': stockcode,
                'name': 'stockcode',
                'type': 'hidden'
            },
            '买卖方式': {
                'label': 'selected',
                'name': 'bs',
                'conf': {
                    'option_list': bs_conf_op_list
                }
            },
            '关注方式': {
                'label': 'selected',
                'name': 'pricetype',
                'conf': {
                    'option_list': type_conf_op_list,
                }
            },
            '触发价格': {
                'value': str(price),
                'name': 'stockprice',
                'size': 5,
                'describe': 1
            },
            '有效天数': {
                'value': validdays,
                'name': 'validdays',
                'size': 3,
                'describe': 1
            },
            '消息提示': {
                'value': promptinfo,
                'name': 'promptinfo',
                'size': 30
            }
        }
        , '设置', 0, 10, 1, 1, 1)
    return form


# 获取均线配置表格
def get_ave_form(action, msc, stockcode, strategycode, default):
    # 买卖方式下拉选框
    bs_op_list = copy.deepcopy(StrategyCons.op_list_bs_conf)
    type_op_list = StrategyCons.op_list_ave_conf
    strategyid = 0
    avedays = '0'
    validdays = '100'
    promptinfo = '请输入触发提示的扩展信息'
    if default == 1:
        bs_op_list = [parse_util.list_to_dict(bs_op_list, 'value').get(msc.get(StrategyCons.bs_flag))]
        type_op_list = [
            parse_util.list_to_dict(type_op_list, 'value').get(msc.get(StrategyCons.conf_info)['avetype'])]
        validdays = msc.get(StrategyCons.conf_info)['validdays']
        promptinfo = msc.get(StrategyCons.conf_info)['promptinfo']
        avedays = msc.get(StrategyCons.conf_info)['avedays']
        strategyid = msc.get(StrategyCons.id)
    form = html_util.get_form_conf(
        action,
        {
            '策略序号': {
                'value': str(strategyid),
                'name': 'strategyid',
                'type': 'hidden'
            },
            '策略编码': {
                'value': strategycode,
                'name': 'strategycode',
                'type': 'hidden'
            },
            '股票编码': {
                'value': stockcode,
                'name': 'stockcode',
                'type': 'hidden'
            },
            '买卖方式': {
                'label': 'selected',
                'name': 'bs',
                'conf': {
                    'option_list': bs_op_list
                }
            },
            '关注方式': {
                'label': 'selected',
                'name': 'avetype',
                'conf': {
                    'option_list': type_op_list
                }
            },
            '均线天数': {
                'value': avedays,
                'name': 'avedays',
                'size': 5,
                'describe': 1
            },
            '有效天数': {
                'value': validdays,
                'name': 'validdays',
                'size': 3,
                'describe': 1
            },
            '消息提示': {
                'value': promptinfo,
                'name': 'promptinfo',
                'size': 30
            }
        }
        , '设置', 0, 10, 1, 1, 1)
    return form


# 获取macd配置表格
def get_macd_form(action, msc, stockcode, strategycode, default):
    # 买卖方式下拉选框
    bs_op_list = copy.deepcopy(StrategyCons.op_list_bs_conf)
    type_op_list = copy.deepcopy(StrategyCons.op_list_macd_conf)
    strategyid = 0
    macddays = '3'
    validdays = '100'
    promptinfo = '请输入触发提示的扩展信息'
    if default == 1:
        bs_op_list = [parse_util.list_to_dict(bs_op_list, 'value').get(msc.get(StrategyCons.bs_flag))]
        type_op_list = [
            parse_util.list_to_dict(type_op_list, 'value').get(msc.get(StrategyCons.conf_info)['macdtype'])]
        validdays = msc.get(StrategyCons.conf_info)['validdays']
        promptinfo = msc.get(StrategyCons.conf_info)['promptinfo']
        macddays = msc.get(StrategyCons.conf_info)['macddays']
        strategyid = msc.get(StrategyCons.id)
    form = html_util.get_form_conf(
        action,
        {
            '策略序号': {
                'value': str(strategyid),
                'name': 'strategyid',
                'type': 'hidden'
            },
            '策略编码': {
                'value': strategycode,
                'name': 'strategycode',
                'type': 'hidden'
            },
            '股票编码': {
                'value': stockcode,
                'name': 'stockcode',
                'type': 'hidden'
            },
            '买卖方式': {
                'label': 'selected',
                'name': 'bs',
                'conf': {
                    'option_list': bs_op_list
                }
            },
            '关注方式': {
                'label': 'selected',
                'name': 'macdtype',
                'conf': {
                    'option_list': type_op_list
                }
            },
            '观测天数': {
                'value': macddays,
                'name': 'macddays',
                'size': 5,
                'describe': 1
            },
            '有效天数': {
                'value': validdays,
                'name': 'validdays',
                'size': 3,
                'describe': 1
            },
            '消息提示': {
                'value': promptinfo,
                'name': 'promptinfo',
                'size': 30
            }
        }
        , '设置', 0, 10, 1, 1, 1)
    return form


# 获取资金流配置表格
def get_io_form(action, msc, stockcode, strategycode, default):
    # 买卖方式下拉选框
    bs_op_list = copy.deepcopy(StrategyCons.op_list_bs_conf)
    type_op_list = copy.deepcopy(StrategyCons.op_list_io_conf)
    strategyid = 0
    iodays = '0'
    validdays = '100'
    promptinfo = '请输入触发提示的扩展信息'
    if default == 1:
        bs_op_list = [parse_util.list_to_dict(bs_op_list, 'value').get(msc.get(StrategyCons.bs_flag))]
        type_op_list = [
            parse_util.list_to_dict(type_op_list, 'value').get(msc.get(StrategyCons.conf_info)[StrategyCons.iotype])]
        validdays = msc.get(StrategyCons.conf_info)[StrategyCons.validdays]
        promptinfo = msc.get(StrategyCons.conf_info)[StrategyCons.promptinfo]
        iodays = msc.get(StrategyCons.conf_info)['iodays']
        strategyid = msc.get(StrategyCons.id)
    form = html_util.get_form_conf(
        action,
        {
            '策略序号': {
                'value': str(strategyid),
                'name': 'strategyid',
                'type': 'hidden'
            },
            '策略编码': {
                'value': strategycode,
                'name': 'strategycode',
                'type': 'hidden'
            },
            '股票编码': {
                'value': stockcode,
                'name': 'stockcode',
                'type': 'hidden'
            },
            '买卖方式': {
                'label': 'selected',
                'name': 'bs',
                'conf': {
                    'option_list': bs_op_list
                }
            },
            '关注方式': {
                'label': 'selected',
                'name': 'iotype',
                'conf': {
                    'option_list': type_op_list
                }
            },
            '资金天数': {
                'value': iodays,
                'name': 'iodays',
                'size': 5,
                'describe': 1
            },
            '有效天数': {
                'value': validdays,
                'name': 'validdays',
                'size': 3,
                'describe': 1
            },
            '消息提示': {
                'value': promptinfo,
                'name': 'promptinfo',
                'size': 30
            }
        }
        , '设置', 0, 10, 1, 1, 1)
    return form


if __name__ == '__main__':
    print('start')
    # record_validation('000157', 40)
    # print(get_stock_broken_line('600031', '', 5))
    # print(diagnosis_stock('600031', ''))
    print(rank_board_stock_mio_plus(1, 0, 'BK0987'))
    # print(trigger_result_c(date_util.get_date_str()))
